package cn.com.pajx.pajx_visitor_v3.api;

import android.annotation.SuppressLint;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;

import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.com.pajx.pajx_visitor_v3.BaseApp;
import cn.com.pajx.pajx_visitor_v3.R;
import cn.com.pajx.pajx_visitor_v3.base.BaseActivity;
import cn.com.pajx.pajx_visitor_v3.bean.EventMessage;
import cn.com.pajx.pajx_visitor_v3.ui.view.dialog.LoadingDialog;
import cn.com.pajx.pajx_visitor_v3.utils.AppConstant;
import cn.com.pajx.pajx_visitor_v3.utils.LogUtils;
import cn.com.pajx.pajx_visitor_v3.utils.MediaStoreUtil;
import cn.com.pajx.pajx_visitor_v3.utils.SharePreferencesUtil;
import cn.com.pajx.pajx_visitor_v3.utils.UpdateUtil;

/**
 * create by ruancw on 2024/2/28
 * description APK下载安装
 */
public class DownLoadApk {
    private NotificationManager mNotificationManager;
    private int max;
    private BaseActivity c;

    private long oldProgress;
    private NotificationCompat.Builder builder;
    private File apkFile;
    private PackageManager packageManager;
    private LoadingDialog loadingDialog;

    private static DownLoadApk mDownloadApk;

    public static DownLoadApk getInstant() {
        if (mDownloadApk == null)
            mDownloadApk = new DownLoadApk();
        return mDownloadApk;
    }

    public void downloadAPK(BaseActivity c, String url, PackageManager packageManager) {
        if (url == null)
            // 不下载更新
            return;
        this.c = c;
        loadingDialog = new LoadingDialog(c, true);
        this.packageManager = packageManager;
        new DownloadTask().execute(url);
    }

    @SuppressLint("StaticFieldLeak")
    private class DownloadTask extends AsyncTask<String, Integer, Void> {

        @SuppressLint("ServiceCast")
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            File rootDir = new File(MediaStoreUtil.getBaseMediaStore(c));
            File file = new File(rootDir.getAbsolutePath() + "/update" + File.separator);
            if (!file.exists())
                file.mkdirs();
            try {
                apkFile = new File(file.getAbsolutePath() + File.separator + "pajx_visitor_v2.apk");
                apkFile.createNewFile();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            mNotificationManager = (NotificationManager) BaseApp.getInstance()
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            //适配安卓8.0的消息渠道
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

                NotificationChannel channel = new NotificationChannel("channel_id", "channel_name", NotificationManager.IMPORTANCE_HIGH);
                mNotificationManager.createNotificationChannel(channel);
            }
            builder = new NotificationCompat.Builder(BaseApp.getInstance())
                    .setSmallIcon(R.drawable.pajx_logo)
                    .setProgress(100, 0, false)
                    .setWhen(System.currentTimeMillis())
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setContentTitle("下载更新包");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                builder.setChannelId("channel_id");
            }
        }

        @Override
        protected Void doInBackground(String... params) {
            try {
                URL url = new URL(params[0]);
                HttpURLConnection httpUrl = (HttpURLConnection) url
                        .openConnection();
                max = httpUrl.getContentLength() / 100;// 获取网络文件的大小
                LogUtils.e("max=" + max);
                InputStream is = url.openStream();
                FileOutputStream fos = new FileOutputStream(apkFile);
                byte[] buffer = new byte[1024];
                int len;
                int progress = 0;
                while ((len = is.read(buffer)) != -1) {
                    progress += len;
                    publishProgress(progress);
                    fos.write(buffer, 0, len);
                }
                is.close();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            LogUtils.e("apk_path=" + apkFile);
            if (apkFile.exists() && apkFile.length() > 0) {
                String apkPath = apkFile.getAbsolutePath();
                SharePreferencesUtil.getInstance().putString(AppConstant.APK_PATH, apkPath);
                checkIsAndroidO();
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            long p = values[0];
            if (max == 0) return;
            showProgress("正在下载");
            long progress = p / max;
            if (oldProgress == 0)
                oldProgress = progress;
            if (progress == oldProgress)
                return;
            else
                oldProgress = progress;

            if (progress != 100) {
                EventBus.getDefault().post(new EventMessage(AppConstant.DOWNLOAD_PROGRESS, progress + "%"));
                builder.setProgress(100, (int) progress, false);
                builder.setContentTitle("下载更新包      " + progress + "%");
            } else {
                hideProgress();
                builder.setProgress(100, 100, false);
                builder.setContentTitle("下载完成");
            }
//            mNotificationManager.notify(100, builder.build());
        }

    }

    /**
     * 安装apk
     *
     * @param c
     */
    public void installAPK(BaseActivity c) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        //适配7.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            String apk_path = SharePreferencesUtil.getInstance().getString(AppConstant.APK_PATH);
            Uri contentUri = FileProvider.getUriForFile(c, "cn.com.pajx.pajx_visitor_v2.provider", new File(apk_path));
            install.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        c.startActivity(install);// 安装
    }

    /**
     * 判断是否是8.0，需要处理未知应用来源权限问题,否则直接安装
     */
    private void checkIsAndroidO() {
        if (Build.VERSION.SDK_INT >= 26) {
            boolean b = packageManager.canRequestPackageInstalls();
            if (b) {
                installAPK(c);//安装应用的逻辑
            } else {
                //请求安装未知应用来源的权限
                UpdateUtil.getInstant().installProcess(c, packageManager);
            }
        } else {
            installAPK(c);
        }
    }

    private void showProgress(String message) {
        if (loadingDialog != null) {
            loadingDialog.setMessage(message).show();
        }
    }

    private void hideProgress() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }
}
